package com.nf.xiaomi.util;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtUtils {
    private static final int TIME=86400000;
    private static final String ISSUER = "xiaomi";
    private static final String KEY = "98acjx79345ofchd79awpdjp85943";

    public static void main(String[] args) {
        String jwtToken = createJwt("040728xjt"); // 假设传入了您的createJwt方法返回的JWT令牌
        parseJwt(jwtToken);
    }
    //创建一个JWT
    public static String createJwt(String pwd){
        Date now = new Date();
        Date expiration = new Date(now.getTime() + TIME);
        JwtBuilder JWT = Jwts.builder()
                .setSubject("login")
                .setIssuer(ISSUER)
                .signWith(SignatureAlgorithm.HS256, KEY)
                .setIssuedAt(now)
                .setExpiration(expiration)
                .claim("password", pwd);
        String token = JWT.compact();
        return token;
    }

    //解析JWT
    public static void parseJwt(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(KEY)
                .parseClaimsJws(token)
                .getBody();

        String subject = claims.getSubject();
        String issuer = claims.getIssuer();
        Date issuedAt = claims.getIssuedAt();
        Date expiration = claims.getExpiration();
        String password = claims.get("password", String.class);

        System.out.println("Subject: " + subject);
        System.out.println("Issuer: " + issuer);
        System.out.println("Issued At: " + issuedAt);
        System.out.println("Expiration: " + expiration);
        System.out.println("Password: " + password);
    }

}
